<template>
  <div class="search">
    <searchBox :searchWord="searchWord"></searchBox>
    <div class="search-other" v-show="searchWord === ''">
      <searchHistroy v-if="historyTags && historyTags.length" :historyTags="historyTags" @clickTag="searchTag"
        @updateHistoryList="getHistoryRecord"></searchHistroy>
      <recommendTag v-if="tags.length" :tags="tags" @clickTag="searchTag"></recommendTag>
    </div>
    <div class="search-content" v-show="searchWord !== '' && searchResultList.length">
      <!-- <searchVideo></searchVideo> -->
      <videoList @fromVideoListInfo="fromVideoListData" :videoResultList="searchResultList" @getNextPage="getSearchVideo" :listFinished="finished"
        :listLoading="loading"></videoList>
    </div>
    <div class="empty" v-show="searchWord !== '' && !searchResultList.length">
      <van-empty image="search" description="暂无搜索结果" image-size="50px" />
    </div>
  </div>
</template>

<script>
import videoList from './compoments/videoList.vue'
import searchBox from './search/searchBox.vue'
import searchHistroy from './search/searchHistroy.vue'
import recommendTag from './search/recommendTag.vue'
// import searchVideo from './search/searchVideo.vue'
import { getHotSearchTags, getSearchContent } from '../util/api'
export default {
  components: {
    searchBox,
    searchHistroy,
    recommendTag,
    videoList
  },
  data() {
    return {
      searchWord: '',//搜索词
      searchResultList: [],//搜索结果（视频）
      tags: [],//热门标签数据
      historyTags: [],//历史搜索数据
      page: 1,//视频页码
      finished: false,
      loading: true
    }
  },
  methods: {
    //热门组件点击tag，传keyword
    searchTag(name) {
      this.searchWord = name
    },
    //根据搜索词和页码获取对应的视频(数据差 视频时长 和 作者 )
    async getSearchVideo() {
      if(this.searchWord == '') return
      this.historySearch(this.searchWord)//存本地作为历史记录
      let params = {
        "contentType": 4, //0：全部 1：H5 2：文档 3：图片 4：视频
        "pageNumber": this.page,// 页码，默认第一页
        // "pageSize": 0,//页面大小，默认10条
        "searchText": this.searchWord//搜索字符串
      }
      try {
        this.loading = true
        const dataMsg = await getSearchContent(params)
        const { code, data } = dataMsg.data
        if (code === '000000') {
          const { list, page } = data
          if (list.length) {
            list.forEach(e => {
              this.searchResultList.push({
                coverUrl: e.coverUrl,//封面
                duration: e.hzbVideo.duration,//视频时长
                contentTitle: e.contentTitle,//title
                author: e.institutionName,//作者
                tagName: e.tags[0] ? e.tags[0].tagName : "",//标签
                h5Url: e.h5Url//跳转需要的信息
              })
            });
            this.page++//请求拿到数据之后页数加一，方便下次请求下一页
            console.log(this.searchResultList, "通过搜索词和翻页得到的数据");
            //显示加载成功
            this.loading = false
          }
          //计算一下最后一页的条数，如果到达最后一页，调用就不再发请求
          const lastPageCount = page.totalCount % page.pageSize
          if (lastPageCount == list.length) {
            this.finished = true
          }
        }
      } catch (error) {
        console.log(error);
        //显示加载完成
        this.finished = true
        this.loading = false
      }

    },
    //查询热门标签
    async getHotTags() {
      try {
        const dataMsg = await getHotSearchTags()
        const { code, data } = dataMsg.data
        if (code === '000000') {
          const { list } = data
          if (list.length) {
            this.tags = [...list]
          }
        }
      } catch (error) {
        console.log('error');
      }

    },
    //搜索词存本地作为历史记录
    historySearch(keyWord) {
      if (keyWord == '') return
      let flag = this.historyTags.indexOf(keyWord)
      //如果原数组没有这个搜索词，那就加上去
      if (flag == -1) {
        if (this.historyTags.length < 10) {
          this.historyTags.unshift(keyWord)
        } else {
          this.historyTags.pop()
          this.historyTags.unshift(keyWord)
        }
      } else {
        //如果有这个元素，那就提到最前面
        this.historyTags.splice(flag, 1)
        this.historyTags.unshift(keyWord)
      }
      localStorage.setItem("zxjtSearchHistory", JSON.stringify(this.historyTags))
    },
    //从本地取历史记录
    getHistoryRecord() {
      let h = localStorage.getItem('zxjtSearchHistory')
      this.historyTags = JSON.parse(h)
      console.log("取值");
      return JSON.parse(h)
    },
    sensorsTrack(video_id, video_name) {
      $sensorsTrack('financing_videoZoneSearchResult', {
        search_keyword: this.searchWord,
        result_type: '4',
        click_result_code: video_id,
        click_result_name: video_name
      });
    },
    fromVideoListData(vlData) {
      if (vlData.type = 'click') {
        this.sensorsTrack(vlData.videoLiveId, vlData.title)
      }
    }
  },
  watch: {
    //搜索词一旦变化就请求数据
    searchWord() {
      this.page = 1//重置页码
      this.finished = false//重置加载状态
      this.searchResultList = []
      this.getSearchVideo()
    },

  },
  mounted() {
    this.getHotTags()
    this.historyTags = this.getHistoryRecord() ? this.getHistoryRecord() : []
    console.log(this.historyTags);
  }
}
</script>

<style scoped lang="less">
.search {
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  .search-other {
    margin-top: 115px;
  }

  .search-content {
    margin-top: 115px;
    margin-left: 30px;
    width: 100%;
  }

  .empty {
    width: 100%;
    height: 80%;
    display: flex;
    justify-content: center;
    align-items: center;

    /deep/ .van-empty__image {
      width: 485px;
      height: 485px;
    }

    /deep/ .van-empty__description {
      font-size: 26px;
    }
  }
}
</style>